/**
 * Created by Tofik Mamishov on 25.09.2014.
 */
var mongoose = require('mongoose');
var log = require('./log')(module);
var config = require('./config');

mongoose.connect(config.get('mongoose:uri'));
var db = mongoose.connection;

db.on('error', function (err) {
    log.error('connection error:', err.message);
});
db.once('open', function callback() {
    log.info('Connected to DB!');
});

var Schema = mongoose.Schema;
/**
 * Account roles.
 * @type {number}
 */
ADMIN = '0';
USER = '1';
/**
 * Social network.
 * @type {Schema}
 */
var societySchema = new Schema({
    _id: {
        type: Number,
        unique: true,
        required: true
    },
    name: {
        type: String,
        unique: true,
        required: true
    },
    icon: {
        type: String,
        required: true
    },
    url: {
        type: String,
        required: true
    }
});
/**
 * Account of user.
 * @type {Schema}
 */
var accountSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    role: {
        type: String,
        enum: [ADMIN, USER],
        required: true
    }
});
/**
 * Relation between a user account and a social network.
 * Used to store token of a social network.
 * @type {Schema}
 */
var societyAccountSchema = new Schema({
    _account: {
        type: Schema.Types.ObjectId,
        ref: 'Account',
        required: true
    },
    _society: {
        type: Number,
        ref: 'Society',
        required: true
    },
    profileId: {
        type: String,
        required: true
    }
});
/**
 * Bucket type.
 * @type {Schema}
 */
var bucketTypeSchema = new Schema({
    _id: {
        type: Number,
        unique: true,
        required: true
    },
    name: {
        type: String,
        required: true
    }
});
/**
 * Bucket.
 * @type {Schema}
 */
var bucketSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    type: {
        type: Number,
        ref: 'BucketType',
        required: true
    },
    lat: {
        type: Number,
        required: true
    },
    lng: {
        type: Number,
        required: true
    },
    photo: {
        type: String,
        required: true
    },
    _createdBy: {
        type: Schema.Types.ObjectId,
        ref: 'Account',
        required: true
    }
});

var Account = mongoose.model('Account', accountSchema);
var Society = mongoose.model('Society', societySchema);
var SocietyAccount = mongoose.model('SocietyAccount', societyAccountSchema);
var BucketType = mongoose.model('BucketType', bucketTypeSchema);
var Bucket = mongoose.model('Bucket', bucketSchema);

module.exports.mongoose = mongoose;
module.exports.Society = Society;
module.exports.Account = Account;
module.exports.SocietyAccount = SocietyAccount;
module.exports.BucketType = BucketType;
module.exports.Bucket = Bucket;